{% extends "base.html" %}

{% block title %}仪表板 - Alist-MikananiRss WebUI{% endblock %}

{% block extra_css %}
<style>
    .dashboard-container {
        display: flex;
        flex-direction: column;
        gap: 1.5rem;
    }

    .dashboard-hero {
        border: none;
        border-radius: 1.5rem;
        padding: 1.5rem;
        background: linear-gradient(135deg, #f5f7ff, #ffffff);
        box-shadow: var(--webui-shadow-md);
    }

    .dashboard-hero .hero-header {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        gap: 1rem;
        flex-wrap: wrap;
    }

    .hero-date {
        font-size: 2.5rem;
        font-weight: 700;
        line-height: 1;
    }

    .hero-weekday {
        color: var(--webui-secondary);
        margin-top: 0.35rem;
    }

    .hero-actions {
        display: flex;
        align-items: center;
        gap: 0.75rem;
    }

    .hero-status {
        display: flex;
        align-items: center;
        gap: 0.5rem;
        font-weight: 600;
    }

    .status-dot {
        width: 10px;
        height: 10px;
        border-radius: 50%;
        display: inline-block;
    }

    .status-dot--active {
        background-color: var(--webui-success);
        animation: pulse 2s infinite;
    }

    .status-dot--inactive {
        background-color: var(--webui-danger);
    }

    .status-dot--unknown {
        background-color: var(--webui-secondary);
    }

    .hero-support-text {
        display: flex;
        flex-direction: column;
        gap: 0.35rem;
        margin-top: 1rem;
        color: var(--webui-secondary);
    }

    .hero-support-text .hero-updated {
        font-size: 0.9rem;
    }

    .status-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
        gap: 1rem;
    }

    .status-card {
        border: none;
        border-radius: 1.25rem;
        padding: 1rem 1.25rem;
        background-color: var(--webui-bg-light);
        box-shadow: var(--webui-shadow-sm);
        display: flex;
        flex-direction: column;
        gap: 0.5rem;
        min-height: 140px;
    }

    .metric-label {
        color: var(--webui-secondary);
        font-size: 0.9rem;
    }

    .metric-value {
        font-size: 1.75rem;
        font-weight: 600;
    }

    .metric-note {
        color: var(--webui-secondary);
        font-size: 0.8rem;
    }

    .dashboard-section {
        border: none;
        border-radius: 1.5rem;
        box-shadow: var(--webui-shadow-sm);
    }

    .dashboard-section .card-header {
        border: none;
        background-color: transparent;
        padding-bottom: 0.25rem;
    }

    .dashboard-section .card-body {
        padding-top: 0.5rem;
    }

    .control-actions {
        display: grid;
        gap: 0.75rem;
        grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
    }

    .control-actions .btn {
        border-radius: 0.85rem;
        padding: 0.85rem;
        font-weight: 600;
    }

    .recent-activity-list {
        display: flex;
        flex-direction: column;
        gap: 0.75rem;
    }

    .recent-activity-item {
        display: flex;
        gap: 0.75rem;
        align-items: flex-start;
        padding: 0.9rem 1rem;
        border-radius: 1.1rem;
        background-color: rgba(79, 70, 229, 0.06);
    }

    .recent-activity-icon {
        font-size: 1.2rem;
        flex-shrink: 0;
    }

    .recent-activity-meta {
        display: flex;
        flex-direction: column;
        gap: 0.25rem;
    }

    .recent-activity-time {
        color: var(--webui-secondary);
        font-size: 0.85rem;
    }

    .empty-placeholder {
        text-align: center;
        padding: 2rem 1rem;
        color: var(--webui-secondary);
    }

    @media (min-width: 992px) {
        .dashboard-container {
            display: grid;
            grid-template-columns: 2fr 1.1fr;
            gap: 1.25rem;
        }

        .dashboard-hero {
            grid-column: 1 / -1;
        }

        .status-grid {
            grid-column: 1 / -1;
        }

        .control-card {
            grid-column: 1 / 2;
        }

        .recent-card {
            grid-column: 2 / 3;
            align-self: stretch;
        }
    }

    @media (max-width: 768px) {
        .hero-header {
            flex-direction: column;
            align-items: flex-start;
        }

        .hero-actions {
            width: 100%;
            justify-content: space-between;
        }
    }

    @media (max-width: 576px) {
        .dashboard-hero {
            padding: 1.25rem;
            border-radius: 1.25rem;
        }

        .hero-date {
            font-size: 2rem;
        }

        .hero-actions {
            width: 100%;
            justify-content: space-between;
        }

        .status-card {
            min-height: auto;
        }

        .recent-activity-item {
            flex-direction: column;
        }
    }
</style>
{% endblock %}

{% block content %}
<div class="fade-in">
    <div class="dashboard-container">
        <div class="dashboard-hero">
            <div class="hero-header">
                <div>
                    <div class="hero-date" id="heroDate">--</div>
                    <div class="hero-weekday" id="heroWeekday">加载中</div>
                </div>
                <div class="hero-actions">
                    <div class="hero-status">
                        <span class="status-dot status-dot--unknown" id="systemStatusDot"></span>
                        <span id="systemStatusText">检测中...</span>
                    </div>
                    <div class="d-flex align-items-center gap-2">
                        <button class="btn btn-light" id="refreshButton" onclick="refreshDashboard()">
                            <i class="bi bi-arrow-clockwise me-1"></i>
                            刷新
                        </button>
                        <button class="btn btn-outline-primary" id="autoRefreshButton" onclick="toggleAutoRefresh()">
                            <i class="bi bi-play-circle me-1" id="autoRefreshIcon"></i>
                            <span id="autoRefreshLabel">自动刷新</span>
                        </button>
                    </div>
                </div>
            </div>
            <div class="hero-support-text">
                <span id="heroSummary">正在加载系统信息...</span>
                <span class="hero-updated" id="heroUpdated">最后更新：--</span>
            </div>
        </div>

        <div class="status-grid">
            <div class="status-card">
                <span class="metric-label">CPU 使用率</span>
                <span class="metric-value" id="cpuUsageValue">--%</span>
                <span class="metric-note" id="cpuUsageNote">等待更新</span>
            </div>
            <div class="status-card">
                <span class="metric-label">内存使用率</span>
                <span class="metric-value" id="memoryUsageValue">--%</span>
                <span class="metric-note" id="memoryUsageNote">等待更新</span>
            </div>
            <div class="status-card">
                <span class="metric-label">磁盘使用率</span>
                <span class="metric-value" id="diskUsageValue">--%</span>
                <span class="metric-note" id="diskUsageNote">等待更新</span>
            </div>
        </div>

        <div class="card dashboard-section control-card">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="bi bi-sliders me-2"></i>
                    运行控制
                </h5>
            </div>
            <div class="card-body">
                <div class="mb-3">
                    <span class="metric-label d-block mb-2">订阅服务状态</span>
                    <div id="systemControls" class="control-actions">
                        <div class="empty-placeholder">
                            <div class="loading-spinner"></div>
                            <div class="mt-2">加载中...</div>
                        </div>
                    </div>
                </div>
                <div class="metric-note">可在此启动、停止或重启订阅服务。</div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    let autoRefreshEnabled = false;

    document.addEventListener('DOMContentLoaded', () => {
        setActiveNav('dashboard');
        updateHeroDate();
        loadDashboard();
    });

    function updateHeroDate() {
        const now = new Date();
        const dateText = now.toLocaleDateString('zh-CN', { month: 'long', day: 'numeric' });
        const weekdayText = now.toLocaleDateString('zh-CN', { weekday: 'long' });
        document.getElementById('heroDate').textContent = dateText;
        document.getElementById('heroWeekday').textContent = weekdayText;
    }

    async function loadDashboard() {
        try {
            const status = await loadSystemStatus();
            await renderSystemControls(status.service_status || status.status);
            document.getElementById('heroUpdated').textContent = `最后更新：${formatTime(new Date())}`;
        } catch (error) {
            console.error('加载仪表板数据失败:', error);
            showNotification('加载数据失败: ' + error.message, 'danger');
        }
    }

    async function loadSystemStatus() {
        const status = await fetchServiceStatus();

        const dot = document.getElementById('systemStatusDot');
        const text = document.getElementById('systemStatusText');
        const summary = document.getElementById('heroSummary');

        const state = status.service_status || status.status;

        if (state === 'running') {
            dot.className = 'status-dot status-dot--active';
            text.textContent = '运行中';
            summary.textContent = '订阅服务已启动并保持监控。';
        } else if (state === 'stopped') {
            dot.className = 'status-dot status-dot--inactive';
            text.textContent = '已停止';
            summary.textContent = '订阅服务已停止，可根据需要重新启动。';
        } else {
            dot.className = 'status-dot status-dot--unknown';
            text.textContent = '未知状态';
            summary.textContent = '暂时无法获取状态，请稍后刷新。';
        }

        updateMetric('cpuUsageValue', 'cpuUsageNote', status.cpu_usage, 'CPU 使用率');
        updateMetric('memoryUsageValue', 'memoryUsageNote', status.memory_usage, '内存使用率');
        updateMetric('diskUsageValue', 'diskUsageNote', status.disk_usage, '磁盘使用率');

        return status;
    }

    function updateMetric(valueId, noteId, rawValue, label) {
        const valueEl = document.getElementById(valueId);
        const noteEl = document.getElementById(noteId);

        if (typeof rawValue === 'number') {
            valueEl.textContent = `${rawValue}%`;
            if (rawValue < 60) {
                noteEl.textContent = `${label}稳定`; 
            } else if (rawValue < 85) {
                noteEl.textContent = `${label}略高，建议关注`; 
            } else {
                noteEl.textContent = `${label}偏高，建议排查`; 
            }
        } else {
            valueEl.textContent = '--%';
            noteEl.textContent = `暂无${label}数据`;
        }
    }

    async function renderSystemControls(status) {
        const container = document.getElementById('systemControls');

        if (status === 'running') {
            container.innerHTML = `
                <button class="btn btn-danger" onclick="stopSystem()">
                    <i class="bi bi-stop-circle me-2"></i>停止服务
                </button>
                <button class="btn btn-warning" onclick="restartSystem()">
                    <i class="bi bi-arrow-repeat me-2"></i>重启服务
                </button>
            `;
        } else {
            container.innerHTML = `
                <button class="btn btn-primary" onclick="startSystem()">
                    <i class="bi bi-play-circle me-2"></i>启动服务
                </button>
            `;
        }
    }

    async function controlService(action) {
        try {
            return await apiCall(`/api/admin/service/${action}`, { method: 'POST' });
        } catch (error) {
            return await apiCall(`/api/admin/system/${action}`, { method: 'POST' });
        }
    }

    async function startSystem() {
        confirmAction('确定要启动服务吗？', async () => {
            try {
                showNotification('正在启动服务...', 'info');
                await controlService('start');
                showNotification('服务启动成功', 'success');
                await loadDashboard();
            } catch (error) {
                showNotification('启动失败: ' + error.message, 'danger');
            }
        });
    }

    async function stopSystem() {
        confirmAction('确定要停止服务吗？', async () => {
            try {
                showNotification('正在停止服务...', 'info');
                await controlService('stop');
                showNotification('服务停止成功', 'success');
                await loadDashboard();
            } catch (error) {
                showNotification('停止失败: ' + error.message, 'danger');
            }
        });
    }

    async function restartSystem() {
        confirmAction('确定要重启服务吗？', async () => {
            try {
                showNotification('正在重启服务...', 'info');
                await controlService('restart');
                showNotification('服务重启成功', 'success');
                await loadDashboard();
            } catch (error) {
                showNotification('重启失败: ' + error.message, 'danger');
            }
        });
    }

    function toggleAutoRefresh() {
        autoRefreshEnabled = !autoRefreshEnabled;
        const icon = document.getElementById('autoRefreshIcon');
        const label = document.getElementById('autoRefreshLabel');

        if (autoRefreshEnabled) {
            icon.className = 'bi bi-pause-circle me-1';
            label.textContent = '停止自动刷新';
            startAutoRefresh(loadDashboard, 30000);
            showNotification('已开启自动刷新', 'success');
        } else {
            icon.className = 'bi bi-play-circle me-1';
            label.textContent = '自动刷新';
            stopAutoRefresh();
            showNotification('已停止自动刷新', 'info');
        }
    }

    window.refreshDashboard = function() {
        loadDashboard();
        showNotification('仪表板已刷新', 'info');
    };

    window.toggleAutoRefresh = toggleAutoRefresh;
    window.startSystem = startSystem;
    window.stopSystem = stopSystem;
    window.restartSystem = restartSystem;
</script>
{% endblock %}
